package com.campus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.common.LearnUnitIsNotChptContants;
import com.campus.mapper.LearnUnitMapper;
import com.campus.mapping.LearnUnitMapping;
import com.campus.model.TCourseLearnUnit;
import com.campus.model.dto.TCourseLearnUnitCreateDto;
import com.campus.model.vo.TCourseLearnUnitSelectVo;
import com.campus.service.ILearnUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class LearnUnitServiceImpl extends ServiceImpl<LearnUnitMapper, TCourseLearnUnit>
        implements ILearnUnitService {

    @Autowired
    private LearnUnitMapper learnUnitMapper;
    @Override
    public Integer createLearnUnit(TCourseLearnUnitCreateDto unitCreateDto) {

        TCourseLearnUnit tCourseLearnUnit = LearnUnitMapping.INSTANCE.CreatetoLearnUnit(unitCreateDto);
        return learnUnitMapper.insert(tCourseLearnUnit);

    }



    public List<TCourseLearnUnitSelectVo> getChildren(Long fatherId){

        QueryWrapper<TCourseLearnUnit> qw = new QueryWrapper();
        qw.eq("father_id",fatherId);
        qw.eq("is_chpt", LearnUnitIsNotChptContants.IS_NOT_CHPT); //不是章单元（子节点）
        List<TCourseLearnUnit> list = learnUnitMapper.selectList(qw);
        return LearnUnitMapping.INSTANCE.toSelectVoList(list);
    }
    public List<TCourseLearnUnitSelectVo> getLearnUnitChildren(List<TCourseLearnUnitSelectVo> list) {

        for (TCourseLearnUnitSelectVo vo : list) {
            List<TCourseLearnUnitSelectVo> children = getChildren(vo.getId());

            if (children.size() > 0) { //有子节点
                vo.setChildren(children);
                getLearnUnitChildren(vo.getChildren());
            }

        }
        return list;
    }

    public List<TCourseLearnUnitSelectVo> getLearnUnitByCourseId(Long courseId){

        QueryWrapper<TCourseLearnUnit> qw = new QueryWrapper();
        qw.eq(!StringUtils.isEmpty(courseId),"course_id",courseId);
//        qw.eq("father_id",0);
        qw.eq("is_chpt", LearnUnitIsNotChptContants.IS_CHPT); //是章单元（父节点）
        List<TCourseLearnUnit> list = learnUnitMapper.selectList(qw);
        List<TCourseLearnUnitSelectVo> selectVoList = LearnUnitMapping.INSTANCE.toSelectVoList(list);
        return getLearnUnitChildren(selectVoList);

    }
}
